//
//  TL_CommentReplyListViewController.m
//  WXReader
//
//  Created by TSL on 2021/4/15.
//  Copyright © 2021 Andrew. All rights reserved.
//

#import "TL_CommentReplyListViewController.h"

#import "TL_CommentsTableViewCell.h"

#import "TL_AppraiseDetailHeaderView.h"

#import "CXTextView.h"

#import "TL_AppraiseDetailModel.h"

#import <IQKeyboardManager/IQKeyboardManager.h>

@interface TL_CommentReplyListViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
{
    CGFloat keyboardHeight;     //键盘高度
    CGFloat commentViewHeight;
}

@property (nonatomic, strong) CXTextView *ctView;

@property (nonatomic, strong) UIView *cbView;

@property (nonatomic, strong) TL_AppraiseDetailModel *aDetailModel;

@end

@implementation TL_CommentReplyListViewController
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [IQKeyboardManager sharedManager].enable = YES;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initialize];
    [self createSubviews];
    [self netRequest];
}

- (void)initialize {
    
    UILabel *navTitleLabel = [TL_UIFactory labelWithBackgroundColor:UIColor.clearColor font:SYSTEM_FONT(16) textColor:kBlackColor];
    navTitleLabel.textAlignment = NSTextAlignmentCenter;
    navTitleLabel.text = WXLocalizedString(@"评论详情");
    [self.navigationBar addSubview:navTitleLabel];
    
    [navTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.navigationBar);
        make.height.mas_equalTo(44);
    }];
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotification object:nil];
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotification object:nil];
}

- (void)backEvent {
    [self dismissViewControllerAnimated:YES completion:^{
            
    }];
}

- (void)createSubviews {
    [self.mainTableViewGroup registerClass:TL_CommentsTableViewCell.class forCellReuseIdentifier:NSStringFromClass(TL_CommentsTableViewCell.class)];
    [self.mainTableViewGroup registerClass:TL_AppraiseDetailHeaderView.class forCellReuseIdentifier:NSStringFromClass(TL_AppraiseDetailHeaderView.class)];
    self.mainTableViewGroup.delegate = self;
    self.mainTableViewGroup.dataSource = self;
    [self.view addSubview:self.mainTableViewGroup];
    
    [self.mainTableViewGroup mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.navigationBar.mas_bottom);
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(-PUB_TABBAR_HEIGHT);
    }];
    
    self.cbView = [[UIView alloc] init];
    self.cbView.backgroundColor = kGrayViewColor;
    [self.view addSubview:self.cbView];
    
    [self.cbView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(PUB_TABBAR_HEIGHT);
    }];
    
    MK_WEAK_SELF
    self.ctView = [[CXTextView alloc] initWithFrame:CGRectMake(kHalfMargin, kQuarterMargin, SCREEN_WIDTH - kMargin, 30)];
    self.ctView.placeholder = [NSString stringWithFormat:WXLocalizedString(@"回复 ＠%@"), [TL_UtilsHelper formatStringWithObject:self.commentModel.nickname]];
    self.ctView.maxLine = 5;
    self.ctView.maxLength = 200;
    self.ctView.font = kMainFont;
    self.ctView.backgroundColor = kWhiteColor;
    self.ctView.layer.cornerRadius = 15;
    self.ctView.textHeightChangeBlock = ^(CGFloat height) {
        SS(strongSelf)
        strongSelf->commentViewHeight = height;
        
        [weakSelf.cbView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(strongSelf->keyboardHeight + height + kHalfMargin);
        }];
    };
    self.ctView.returnHandlerBlock = ^{
        [weakSelf sendCommentNetRequest];
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    };
    [self.cbView addSubview:self.ctView];
    
    [self.mainTableViewGroup addHeaderRefreshWithRefreshingBlock:^{
        weakSelf.currentPageNumber = 1;
        [weakSelf netRequest];
    }];
    
    [self.mainTableViewGroup addFooterRefreshWithRefreshingBlock:^{
        weakSelf.currentPageNumber++;
        [weakSelf netRequest];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return self.dataSourceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MK_WEAK_SELF;
    if (indexPath.section == 0) {
        TL_AppraiseDetailHeaderView *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(TL_AppraiseDetailHeaderView.class)];
        if (!cell) {
            cell = [[TL_AppraiseDetailHeaderView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass(TL_AppraiseDetailHeaderView.class)];
        }
        cell.commentProductionClickBlock = ^{
            if (weakSelf.productionType == TL_ProductionTypeComic) {
//                TL_ComicMallDetailViewController *vc = [[TL_ComicMallDetailViewController alloc] init];
//                vc.comic_id = weakSelf.aDetailModel.production_id;
//                [weakSelf.navigationController pushViewController:vc animated:YES];
            } else {
//                TL_BookMallDetailViewController *vc = [[TL_BookMallDetailViewController alloc] init];
//                vc.book_id = weakSelf.aDetailModel.production_id;
//                [weakSelf.navigationController pushViewController:vc animated:YES];
            }
        };
//        cell.aDetailModel = self.aDetailModel;
        cell.commentsDetailModel = self.commentModel;
        cell.productionType = self.productionType;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        TL_CommentsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(TL_CommentsTableViewCell.class)];
        if (!cell) {
            cell = [[TL_CommentsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass(TL_CommentsTableViewCell.class)];
        }
        cell.commentLabel.numberOfLines = 0;
        cell.isReplyList = YES;
        cell.commentModel = [self.dataSourceArray wx_objectOrNilAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.hiddenEndLine = YES;
        
        cell.deleteCommentBlock = ^(TL_CommentsDetailModel *commentsDetailModel,int type) {
            if (type == 0) {
                
                NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:self.dataSourceArray];
                
                [tmpArray removeObject:commentsDetailModel];
                
                self.dataSourceArray = [tmpArray mutableCopy];
                
                weakSelf.commentModel.reply_num = weakSelf.commentModel.reply_num - 1;
                
                [weakSelf.mainTableViewGroup reloadData];
                
            }else{
                
                NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:self.dataSourceArray];
                
                for (TL_CommentsDetailModel *cdModel in self.dataSourceArray) {
                    if (cdModel.uid == commentsDetailModel.uid) {
                        [tmpArray removeObject:cdModel];
                        weakSelf.commentModel.reply_num -= 1;
                    }
                }
                self.dataSourceArray = [tmpArray copy];
                
                [weakSelf.mainTableViewGroup reloadData];
            }
        };
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 44;
    }
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *sectionView = [TL_UIFactory view];
    
    if (section == 1) {
        UILabel *sectionLabel = [TL_UIFactory labelWithBackgroundColor:UIColor.clearColor font:kMainFont textColor:kBlackColor];
        sectionLabel.text = [NSString stringWithFormat:WXLocalizedString(@"全部回复（%@）"),[TL_UtilsHelper formatStringWithInteger:self.commentModel.reply_num]];
        [sectionView addSubview:sectionLabel];
        
        [sectionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(kMargin);
            make.centerY.mas_equalTo(sectionView);
        }];
    }
    
    return sectionView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section==0) {
        return kHalfMargin;
    } else if (self.dataSourceArray.count == 0) {
        return 44;
    }
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *sectionView = [TL_UIFactory view];
    
    if (section == 0) {
        sectionView.backgroundColor = kGrayViewColor;
    } else {
        sectionView.backgroundColor = kWhiteColor;

        UILabel *titleLabel = [TL_UIFactory label];
        titleLabel.font = kMainFont;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = WXLocalizedString(@"暂无评论回复");
        titleLabel.textColor = kGrayTextColor;
        [sectionView addSubview:titleLabel];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(sectionView);
        }];
    }
    return sectionView;
}

- (void)netRequest {

//    if (self.productionType == TL_ProductionTypeComic) {
//        parameters = @{@"page_num":[TL_UtilsHelper formatStringWithInteger:self.currentPageNumber], @"comment_id":[TL_UtilsHelper formatStringWithInteger:self.commentModel.comment_id], @"type":@"2"};
//    } else {
//        parameters = @{@"page_num":[TL_UtilsHelper formatStringWithInteger:self.currentPageNumber], @"comment_id":[TL_UtilsHelper formatStringWithInteger:self.commentModel.comment_id], @"type":@"1"};
//    }
    
    NSMutableDictionary *parameters = [@{
        @"pageNum":[TL_UtilsHelper formatStringWithInteger:self.currentPageNumber],
        @"pageSize":@"10",
    } mutableCopy];
    
    if (self.commentId) {
        [parameters setObject:self.commentId forKey:@"commentId"];
    }else{
        [parameters setObject:[TL_UtilsHelper formatStringWithInteger:self.commentModel.comment_id] forKey:@"commentId"];
    }
    
//    replyDetailGoods
    MK_WEAK_SELF;
    
    [APIManager sendGetRequest:[APIURLManager replyDetailGoods] parameters:parameters model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        [weakSelf.mainTableViewGroup endRefreshing];
        
        if (success) {
            
            if (!self.commentModel) {
                
                self.commentModel = [TL_CommentsDetailModel mj_objectWithKeyValues:requestModel.data[@"nowComment"]];
                
                self.commentModel.reply_num = [requestModel.data[@"replyNum"] intValue];
                
            }
            
            NSArray *commentList = [TL_CommentsDetailModel mj_objectArrayWithKeyValuesArray:requestModel.data[@"replyList"]];
            int currntPage = [requestModel.data[@"current"] intValue];
            int totalPage = [requestModel.data[@"pages"] intValue];
            
            if (weakSelf.currentPageNumber == 1) {
                
                [weakSelf.mainTableViewGroup showRefreshFooter];
                
                weakSelf.dataSourceArray = [[NSMutableArray alloc] initWithArray:commentList];
                
            } else {
                [weakSelf.dataSourceArray addObjectsFromArray:commentList];
            }

            if (totalPage >= currntPage) {
                [weakSelf.mainTableViewGroup hideRefreshFooter];
            }

            [weakSelf.mainTableViewGroup reloadData];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.mainTableViewGroup) {
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    }
}

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)noti
{
    //获取键盘的高度
    keyboardHeight = [[[noti userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    [self.cbView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(keyboardHeight + commentViewHeight + kHalfMargin + kQuarterMargin + 30);
    }];
    [self.cbView.superview layoutIfNeeded];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)noti
{
    keyboardHeight = PUB_TABBAR_OFFSET;
    [self.cbView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(commentViewHeight + PUB_TABBAR_OFFSET + (PUB_TABBAR_HEIGHT - PUB_TABBAR_OFFSET - 30));
    }];
    [self.cbView.superview layoutIfNeeded];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (![self.cbView pointInside:[self.cbView convertPoint:[[touches anyObject] locationInView:self.view] fromView:self.view] withEvent:event]) {
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    }
}

- (void)sendCommentNetRequest
{
    if ([self.ctView.text isEqualToString:@""]) {
        return;
    }
    
    NSString *t_text = self.ctView.text;
    self.ctView.text = @"";
    
    NSString *url = [APIURLManager replyGoods];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [parameters setObject:[TL_UtilsHelper formatStringWithInteger:self.commentModel.comment_id] forKey:@"commentId"];
    
    [parameters setObject:t_text forKey:@"content"];
    
    MK_WEAK_SELF
    
    [APIManager sendPostRequest:url parameters:parameters model:TL_CommentsDetailModel.class success:^(BOOL success, TL_CommentsDetailModel*  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
           
            weakSelf.ctView.placeholder = [NSString stringWithFormat:WXLocalizedString(@"回复 ＠%@"), [TL_UtilsHelper formatStringWithObject:weakSelf.commentModel.nickname]];

            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"评论成功")];
            
            [self netRequest];
            
            [weakSelf.mainTableViewGroup ly_endLoading];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [TL_TopAlertManager showAlertWithError:error defaultText:WXLocalizedString(@"评论失败")];
    }];
}

- (void)setCommentModel:(TL_CommentsDetailModel *)commentModel {
    _commentModel = commentModel;
}

@end
